package StarterCors

import (
	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
)

func init() {
	gs.Object(&WebCorsFilter{}).Export((*web.Filter)(nil))
}

type WebCorsFilter struct {
}

func (f *WebCorsFilter) Invoke(ctx web.Context, chain web.FilterChain) {
	method := ctx.Request().Method
	origin := ctx.Header("Origin")
	ctx.SetHeader("Access-Control-Allow-Origin", origin)
	ctx.SetHeader("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
	ctx.SetHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
	ctx.SetHeader("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
	ctx.SetHeader("Access-Control-Allow-Credentials", "true")

	// 放行所有OPTIONS方法
	if method == "OPTIONS" {
		return
	}
	// 处理请求
	chain.Next(ctx)
}